import { ElMessage } from 'element-plus'
import { ref } from 'vue'

export interface ErrorInfo {
  message: string
  code?: string | number
  details?: any
  timestamp: number
}

export function useErrorHandler() {
  const errors = ref<ErrorInfo[]>([])
  const isLoading = ref(false)

  const handleError = (error: any, customMessage?: string) => {
    console.error('Error occurred:', error)
    
    const errorInfo: ErrorInfo = {
      message: customMessage || getErrorMessage(error),
      code: error?.code || error?.status,
      details: error,
      timestamp: Date.now()
    }
    
    errors.value.push(errorInfo)
    
    // 显示错误消息
    ElMessage.error(errorInfo.message)
    
    return errorInfo
  }

  const getErrorMessage = (error: any): string => {
    if (typeof error === 'string') {
      return error
    }
    
    if (error?.message) {
      return error.message
    }
    
    if (error?.response?.data?.message) {
      return error.response.data.message
    }
    
    if (error?.response?.statusText) {
      return error.response.statusText
    }
    
    return '操作失败，请稍后重试'
  }

  const clearErrors = () => {
    errors.value = []
  }

  const withErrorHandling = async <T>(
    asyncFn: () => Promise<T>,
    errorMessage?: string
  ): Promise<T | null> => {
    try {
      isLoading.value = true
      return await asyncFn()
    } catch (error) {
      handleError(error, errorMessage)
      return null
    } finally {
      isLoading.value = false
    }
  }

  const withLoadingAndError = async <T>(
    asyncFn: () => Promise<T>,
    loadingRef: { value: boolean },
    errorMessage?: string
  ): Promise<T | null> => {
    try {
      loadingRef.value = true
      return await asyncFn()
    } catch (error) {
      handleError(error, errorMessage)
      return null
    } finally {
      loadingRef.value = false
    }
  }

  return {
    errors,
    isLoading,
    handleError,
    getErrorMessage,
    clearErrors,
    withErrorHandling,
    withLoadingAndError
  }
}